package utils

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"gopkg.in/mgo.v2/bson"
	mathRand "math/rand"
	"strings"
	"time"
)

const (
	tmp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345678900"
)

func IsEmpty(str string) bool {
	if strings.TrimSpace(str) == "" {
		return true
	}
	return false
}

//根据bsonID转string
func BsonIdToSId(uid interface{}) string {
	if uid == nil {
		return ""
	} else if u, ok := uid.(string); ok {
		return u
	} else {
		return fmt.Sprintf("%x", string(uid.(bson.ObjectId)))
	}
}

func StringTOBsonId(id string) (bid bson.ObjectId) {
	defer Catch()
	if id != "" {
		bid = bson.ObjectIdHex(id)
	}
	return
}

func Uuid(length int) string {
	ret := []string{}
	r := mathRand.New(mathRand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		index := r.Intn(62)
		ret = append(ret, tmp[index:index+1])
	}
	return strings.Join(ret, "")
}

//生成32位md5字串
func GetMd5String(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}

//obj(string,M)转M,查询用到
func ObjToMap(obj interface{}) *map[string]interface{} {
	data := make(map[string]interface{})
	if s, ok := obj.(string); ok {
		json.Unmarshal([]byte(strings.Replace(s, "'", "\"", -1)), &data)
	} else if s1, ok1 := obj.(map[string]interface{}); ok1 {
		data = s1
	} else if s1, ok1 := obj.(*map[string]interface{}); ok1 {
		return s1
	} else {
		data = nil
	}
	return &data
}

//对象数组转成string数组
func ObjArrToStringArr(old []interface{}) []string {
	if old != nil {
		new := make([]string, len(old))
		for i, v := range old {
			new[i] = v.(string)
		}
		return new
	} else {
		return nil
	}
}

//对象数组转成map数组
func ObjArrToMapArr(old []interface{}) []map[string]interface{} {
	if old != nil {
		new := make([]map[string]interface{}, len(old))
		for i, v := range old {
			new[i] = v.(map[string]interface{})
		}
		return new
	} else {
		return nil
	}
}

//map数组转成对象数组
func MapArrToObjArr(old []map[string]interface{}) []interface{} {
	if old != nil {
		new := make([]interface{}, len(old))
		for i, v := range old {
			new[i] = v
		}
		return new
	} else {
		return nil
	}
}
